package com.alibaba.nacos.naming.utils;

import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.naming.core.v2.pojo.InstancePublishInfo;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import com.google.common.collect.Maps;

import java.util.Map;
import java.util.Objects;
import java.util.Optional;

public class InstanceUtil {

    public static Instance parseToApiInstance(Service service,
                                              InstancePublishInfo instanceInfo) {
        Instance result = new Instance();
        result.setIp(instanceInfo.getIp())
                .setPort(instanceInfo.getPort())
                .setServiceName(service.getGroupedServiceName())
                .setClusterName(instanceInfo.getCluster())
                .setEphemeral(service.isEphemeral())
                .setHealthy(instanceInfo.isHealthy());

        Map<String, Object> extendDatum = instanceInfo.getExtendDatum();
        Optional.ofNullable(extendDatum.remove("customInstanceId")).ifPresent(v -> result.setInstanceId((String) v));
        Optional.ofNullable(extendDatum.remove("publishInstanceEnable")).ifPresent(v -> result.setEnabled((boolean) v));
        Optional.ofNullable(extendDatum.remove("publishInstanceWeight")).ifPresent(v -> result.setWeight((Double) v));

        extendDatum = Maps.filterValues(extendDatum, Objects::nonNull);
        Map<String, String> map = Maps.transformValues(extendDatum, String::valueOf);
        result.setMetadata(map);
        return result;
    }


}
